package com.rest.demo.functional.concurrent;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.StampedLock;

/**
 * @author Administrator
 * @decription
 * @Date 2018-01-31 8:57
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newWorkStealingPool(2);
        Map<String,String> map = new HashMap<String,String>();
        StampedLock lock = new StampedLock ();
        executor.submit(() -> {
            long stamp = lock.writeLock();
            try {
                ConcurrentUtils.sleep(1);
                map.put("foo","bar");
            } finally {
                lock.unlockWrite(stamp);
            }
        });
        Runnable readTask = () -> {
            long stamp = lock.readLock();
            try {
                System.out.println(map.get("foo"));
                ConcurrentUtils.sleep(1);
            } finally {
                lock.unlockRead(stamp);
            }
        };
        executor.submit(readTask);
        executor.submit(readTask);
        ConcurrentUtils.stop(executor);
    }
}
